<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Procedures &amp; functions</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Visual Basic, learn Visual Basic, procedures, functions, tutorial, programming language">
<meta name="description" content="This part of the Visual Basic tutorial covers 
procedures &amp; functions in Visual Basic.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Procedures &amp; functions</h1>

<p>
In this part of the tutorial, you will learn Visual Basic procedures &amp; functions. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>

<p>
We use procedures and functions to create modular programs. Visual Basic statements 
are grouped in a block enclosed by Sub, Function and matching End statements. The
difference between the two is that functions return values, procedures don't. 
</p>

<p>
A procedure and function is a piece of code in a larger program. They perform a specific task. 
The advantages of using procedures and functions are:
</p>

<ul>
<li>Reducing duplication of code</li>
<li>Decomposing complex problems into simpler pieces</li>
<li>Improving clarity of the code</li>
<li>Reuse of code</li>
<li>Information hiding</li>
</ul>


<h2>Procedures</h2>

<p>
A procedure is a block of Visual Basic statements inside <code>Sub</code>, 
<code>End Sub</code> statements. Procedures do not return values. 
</p>

<pre class="code">
Option Strict On


Module Example

    Sub Main()
       
        SimpleProcedure()
        
    End Sub
    
    Sub SimpleProcedure()
        Console.WriteLine("Simple procedure")
    End Sub
    
End Module
</pre>

<p>
This example shows basic usage of procedures. In our program, we have two
procedures. The Main() procedure and the user defined SimpleProcedure(). 
As we already know, the Main() procedure is the entry point of a Visual Basic
program.
</p>

<pre class="explanation">
SimpleProcedure()
</pre>

<p>
Each procedure has a name. Inside the Main() procedure,
we <b>call</b> our user defined SimpleProcedure() procedure. 
</p>

<pre class="explanation">
Sub SimpleProcedure()
    Console.WriteLine("Simple procedure")
End Sub
</pre>

<p>
Procedures are defined outside the Main() procedure. 
Procedure name follows the <code>Sub</code> statement.
When we call a procedure inside the Visual Basic program, the 
control is given to that procedure. Statements inside the block of
the procedure are executed.   
</p>

<hr class="btm">

<p>
Procedures can take optional parameters. 
</p>

<pre class="code">
Option Strict On


Module Example

    Sub Main()

        Dim x As Integer = 55
        Dim y As Integer = 32
       
        Addition(x, y)
        
    End Sub
    
    Sub Addition(ByVal k As Integer, ByVal l As Integer)
        Console.WriteLine(k+l)
    End Sub
    
End Module
</pre>

<p>
In the above example, we pass some values to the Addition()
procedure. 
</p>

<pre class="explanation">
Addition(x, y)
</pre>

<p>
Here we call the Addition() procedure and pass two parameters to it.
These parameters are two Integer values. 
</p>

<pre class="explanation">
Sub Addition(ByVal k As Integer, ByVal l As Integer)
    Console.WriteLine(k+l)
End Sub
</pre>

<p>
We define a <b>procedure signature</b>. A procedure signature is a way of describing the 
parameters and parameter types with which a legal call to the function can be made. 
It contains the name of the procedure, its parameters and their type, and 
in case of functions also the return value. The <code>ByVal</code> keyword
specifies how we pass the values to the procedure. In our case, the procedure
obtains two numerical values, 55 and 32. These numbers are added and the result 
is printed to the console. 
</p>

<h2>Functions</h2>

<p>
A function is a block of Visual Basic statements inside <code>Function</code>, 
<code>End Function</code> statements. Functions return values. 
</p>

<p>
There are two basic types of functions. Built-in functions and user defined ones. 
The built-in functions are part of the Visual Basic language. 
There are various mathematical, string or conversion functions.
</p>

<pre class="code">
Option Strict On


Module Example

    Sub Main()
       
        Console.WriteLine(Math.Abs(-23))
        Console.WriteLine(Math.Round(34.56))
        Console.WriteLine("ZetCode has {0} characters", _
            Len("ZetCode"))
        
    End Sub
    
End Module
</pre>

<p>
In the preceding example, we use two math functions and one
string function. Built-in functions help programmers do some
common tasks.
</p>

<hr class="btm">

<p>
In the following example, we have a user defined
function.
</p>

<pre class="code">
Option Strict On


Module Example

    Dim x As Integer = 55
    Dim y As Integer = 32
    
    Dim result As Integer

    Sub Main()

        result = Addition(x, y)
        Console.WriteLine(Addition(x, y))
        
    End Sub
    
    Function Addition(ByVal k As Integer, _
                       ByVal l As Integer) As Integer
        Return k+l
    End Function
    
End Module
</pre>

<p>
Two values are passed to the function. We add these two values and return the
result to the Main() function. 
</p>

<pre class="explanation">
result = Addition(x, y)
</pre>

<p>
Addition function is called. The function returns a result and this
result is assigned to the result variable.
</p>

<pre class="explanation">
Function Addition(ByVal k As Integer, _
                    ByVal l As Integer) As Integer
    Return k+l
End Function
</pre>

<p>
This is the Addition function signature and its body. It also
includes a return data type, for the returned value. In our
case is is an <code>Integer</code>. Values are returned
to the caller with the <code>Return</code> keyword.
</p>


<h2>Passing parameters by value, by reference</h2>

<p>
Visual Basic supports two ways of passing parameters to functions. By value
and by reference. For this, we have two keywords. <code>ByVal</code> and
<code>ByRef</code>. When we pass arguments by value, the function
works only with the copies of the values. This may lead to performance overheads, when we
work with large amounts of data. 
</p>

<p>
When we pass values by reference, the function receives a reference to the actual values. 
The original values are affected, when modified. This way of passing values is more 
time and space efficient. On the other hand, it is more error prone. 
</p>

<p>
Which way of passing arguments should we use? It depends on the situation. Say we have 
a set of data, salaries of employees. If we want to compute some statistics of the data,
we do not need to modify them. We pass by values. If we work with large amounts of data 
and the speed of computation is critical, we pass by reference. If we want to modify
the data, e.g. do some reductions or raises to the salaries, we might pass by reference. 
</p>

<p>
The following two examples cover both concepts. 
</p>


<pre class="code">
Option Strict On


Module Example

    Dim a As Byte = 4
    Dim b As Byte = 7

    Sub Main()
       
        Console.WriteLine("Outside Swap procedure")
        Console.WriteLine("a is {0}", a)
        Console.WriteLine("b is {0}", b)

        Swap(a, b)

        Console.WriteLine("Outside Swap procedure")
        Console.WriteLine("a is {0}", a)
        Console.WriteLine("b is {0}", b)
        
    End Sub
    

    Sub Swap(ByVal a As Byte, ByVal b As Byte) 
        Dim temp As Byte
        temp = a
        a = b
        b = temp
        Console.WriteLine("Inside Swap procedure")
        Console.WriteLine("a is {0}", a)
        Console.WriteLine("b is {0}", b)
    End Sub
  
End Module
</pre>

<p>
The Swap() procedure swaps the numbers between the a, b variables. 
The original variables are not affected. 
</p>

<pre class="explanation">
Dim a As Byte = 4
Dim b As Byte = 7
</pre>

<p>
At the beginning, these two variables are initiated. 
</p>

<pre class="explanation">
Swap(a, b)
</pre>

<p>
We call the Swap() procedure. The procedure takes a, b variables as
parameters.  
</p>

<pre class="explanation">
temp = a
a = b
b = temp
</pre>

<p>
Inside the Swap() procedure, we change the values. Note that the a, b variables are
defined locally. They are valid only inside the Swap() procedure. 
</p>


<pre>
$ ./swap1.exe 
Outside Swap procedure
a is 4
b is 7
Inside Swap procedure
a is 7
b is 4
Outside Swap procedure
a is 4
b is 7
</pre>

<p>
The output shows, that the original variables were not affected. 
</p>

<hr class="btm">

<p>
The next code example passes values to the function by reference. 
The original variables are changed inside the Swap() procedure. 
</p>

<pre class="code">
Option Strict On


Module Example

    Dim a As Byte = 4
    Dim b As Byte = 7

    Sub Main()
       
        Console.WriteLine("Outside Swap procedure")
        Console.WriteLine("a is {0}", a)
        Console.WriteLine("b is {0}", b)

        Swap(a, b)

        Console.WriteLine("Outside Swap procedure")
        Console.WriteLine("a is {0}", a)
        Console.WriteLine("b is {0}", b)
        
    End Sub
    

    Sub Swap(ByRef a As Byte, ByRef b As Byte) 
        Dim temp As Byte
        temp = a
        a = b
        b = temp
        Console.WriteLine("Inside Swap procedure")
        Console.WriteLine("a is {0}", a)
        Console.WriteLine("b is {0}", b)
    End Sub
  
End Module

</pre>

<p>
In this example, calling the Swap() procedure will change the original 
values.
</p>

<pre class="explanation">
Sub Swap(ByRef a As Byte, ByRef b As Byte) 
 ...  
End Sub
</pre>

<p>
Now we use the <code>ByRef</code> keyword to indicate, that
we pass parameters by reference.
</p>

<pre>
$ ./swap2.exe 
Outside Swap procedure
a is 4
b is 7
Inside Swap procedure
a is 7
b is 4
Outside Swap procedure
a is 7
b is 4
</pre>

<p>
Here we see, that the Swap() procedure really changed the values of the variables. 
</p>


<h2>Recursion</h2>

<p>
Recursion, in mathematics and computer science, is a method of defining functions 
in which the function being defined is applied within its own definition. (Wikipedia)
In other words, a recursive function calls itself to do its job.
Recursion is a widely used approach to solve many programming tasks. 
</p>

<p>
A typical example is calculation of the factorial.
</p>

<pre class="code">
Option Strict On


Module Example

    Sub Main()
       
        Console.WriteLine(Factorial(4))
        Console.WriteLine(Factorial(10))
        
    End Sub
    
    Function Factorial(ByVal n As UShort) As UShort
        If (n=0)
            Return 1
        Else
            Return n * Factorial(n-1)
        End If 
       
    End Function
    
End Module
</pre>

<p>
In this code example, we calculate the factorial of two
numbers. 
</p>

<pre class="explanation">
Return n * Factorial(n-1)
</pre>

<p>
Inside the body of the factorial function, we call the factorial function
with a modified argument. The function calls itself.
</p>

<pre>
$ ./recursion.exe 
24
3628800
</pre>

<p>
These are the results.
</p>



<h2>Module scope, procedure scope</h2>

<p>
A <b>scope</b> is the range in which a variable can be referenced.
A variable which is declared inside the procedure has a procedure
scope. It is valid only in this particular procedure.
A variable declared inside a module has a module scope. It is
valid everywhere in the module. 
</p>

<pre class="code">
Option Strict On


Module Example

    Dim a As Byte = 2

    Sub Main()
        Dim b As Byte = 3         

        Console.WriteLine(a)
        SimpleProcedure()
        
    End Sub
    
    Sub SimpleProcedure()
        Console.WriteLine(a)
        ' Console.WriteLine(b)
    End Sub
    
End Module
</pre>

<p>
In the preceding example, we declare two variables. Variable
a has the module scope, variable b has the procedure scope.
</p>

<pre class="explanation">
Dim a As Byte = 2
</pre>

<p>
Variable a is declared inside the Example module, outside the
two procedures. It is valid in both procedures.
</p>

<pre class="explanation">
Sub Main()
    Dim b As Byte = 3         
...
End Sub
</pre>

<p>
The variable b is declared in the Main() procedure.
It is valid only there. It is not valid in the second
procedure.
</p>

<pre class="explanation">
Sub SimpleProcedure()
    Console.WriteLine(a)
    ' Console.WriteLine(b)
End Sub
</pre>

<p>
The statement printing the b variable is commented. If we uncommented
the line, the example would not compile. 
</p>

<hr class="btm">

<pre class="code">
Option Strict On


Module Example

    Dim a As Byte = 2

    Sub Main()
        Dim a As Byte = 3         

        Console.WriteLine(a)
        
    End Sub
    
End Module
</pre>

<p>
In the preceding example, we have declared a variable with the
same name in two different scopes. They do not collide.
The variable declared inside the Main() procedure overrides the
one, declared in the module scope. 
</p>

<pre>
$ ./scope2.exe 
3
</pre>

<p>
Output.
</p>



<h2>Static variables</h2>

<p>
A <b>static</b> variable is a variable that has been allocated statically, 
whose lifetime extends across the entire run of the program. (Wikipedia)
The default, local variables do not retain their value within 
consecutive calls of the function. 
</p>


<pre class="code">
Option Strict On


Module Example

    Sub Main()
       
        NonStatic()
        NonStatic()
        NonStatic()
        NonStatic()
        Console.WriteLine(NonStatic)
        
    End Sub
    
    Function NonStatic() As Integer
        Dim x As Integer = 0
        x += 1
        Return x
    End Function
    
End Module
</pre>

<p>
In the above example, we have a normal, non-static variable. We increment the variable each time the 
function is called. We call the function 5 times. However, non-static variables are initiated for each
call of the function. 
</p>

<pre>
$ ./nonstatic.exe 
1
</pre>

<p>
After 5 function calls the x variable equals to 1. 
</p>

<p>
The static variables are initiated only once, when the function is first called. They retain their
value afterwards. 
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()
       
        StaticFunction()
        StaticFunction()
        StaticFunction()
        StaticFunction()
        Console.WriteLine(StaticFunction)
        
    End Sub
    
    Function StaticFunction() As Integer
        Dim Static x As Integer = 0
        x += 1
        Return x
    End Function
    
End Module
</pre>

<p>
After 5 consecutive calls, the x is equal to 5. 
</p>

<pre class="explanation">
Dim Static x As Byte = 0
</pre>

<p>
Static variables are created with the <code>Static</code>
keyword.
</p>

<pre>
$ ./static.exe 
5
</pre>

<p>
Running the example.
</p>


<p>
In this part of the Visual Basic tutorial, we covered procedures and functions. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem">
<a href="..">Contents</a></span> ‡ <span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified September 4, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

